package com.rainszj.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rainszj.pojo.dto.QueryBlog;
import com.rainszj.pojo.po.Blog;
import com.rainszj.pojo.po.User;
import com.rainszj.pojo.vo.BlogQueryResult;
import com.rainszj.pojo.vo.UpdateBlog;
import com.rainszj.service.BlogService;
import com.rainszj.service.TagService;
import com.rainszj.service.TypeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import static com.rainszj.constant.WebConstant.*;
/**
 * 后台博客展示列表
 *
 * @author rainszj
 */
@Controller
public class BlogController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    /**
     * 下拉框中可供选择的分类
     *
     * @param model
     */
    private void saveTagAndType(Model model) {
        model.addAttribute("types", typeService.listAdminType());
        model.addAttribute("tags", tagService.listAdminTag());
    }

    /**
     * 展示所有的博客列表
     *
     * @return
     */
    @GetMapping("/admin/blogs")
    public String list(@RequestParam(defaultValue = "1", name = "pageNum") Integer pageNum, Model model) {
        PageInfo<BlogQueryResult> pageInfo = PageHelper.startPage(pageNum, ADMIN_PAGE_SIZE).doSelectPageInfo(() -> blogService.listAdminBlog());

        this.saveTagAndType(model);
        model.addAttribute("pageInfo", pageInfo);

        return "admin/blogs";
    }

    /**
     * 动态条件查询博客
     *
     * @return
     */
    @PostMapping("/admin/blogs/search")
    public String toQueryBlog(QueryBlog queryBlog,
                              @RequestParam(defaultValue = "1", name = "pageNum") Integer pageNum,
                              Model model) {
        // 没有任何条件，重定向到 /admin/blogs
        if ("".equals(queryBlog.getTitle()) && queryBlog.getTypeId() == null && queryBlog.getRecommend() == null) {
            return "redirect:/admin/blogs";
        }
        // 有条件查询
        PageHelper.startPage(pageNum, ADMIN_PAGE_SIZE);
        List<BlogQueryResult> queryResults = blogService.listQueryBlog(queryBlog);

        PageInfo<BlogQueryResult> pageInfo = new PageInfo<BlogQueryResult>(queryResults);
        model.addAttribute("pageInfo", pageInfo);
        this.saveTagAndType(model);

        return "admin/blogs";
    }

    /**
     * 删除博客
     *
     * @param id
     * @param attributes
     * @return
     */
    @DeleteMapping("/admin/blogs/{id}")
    public String removeBlogById(@PathVariable("id") Long id, RedirectAttributes attributes) {

        int result = blogService.removeBlog(id);
        if (result > 0) {
            attributes.addFlashAttribute("msg", "删除成功");
        } else {
            attributes.addFlashAttribute("msg", "删除失败");
        }
        return "redirect:/admin/blogs";
    }

    /**
     * 跳转到新增博客页面
     *
     * @param model
     * @return
     */
    @GetMapping("/admin/blogs/addBlog")
    public String toAddBlogPage(Model model) {
        this.saveTagAndType(model);
        return "admin/post";
    }

    /**
     * 新增博客
     *
     * @param blog
     * @return
     */
    @PostMapping("/admin/blogs")
    public String addBlog(Blog blog, RedirectAttributes attributes) {
        // blog.setUser((User) session.getAttribute("loginUser"));
        Subject subject = SecurityUtils.getSubject();
        User loginUser = (User) subject.getSession().getAttribute("loginUser");
        blog.setUser(loginUser);
        // 前端的 type.id 自动封装成 type对象
        Long typeId = blog.getType().getId();
        // 设置博客的分类
        blog.setType(typeService.queryTypeById(typeId));
        // 关联分类表得id
        blog.setTypeId(typeId);
        // 获取tags字符串
        String tagIds = blog.getTagIds();
        // 设置博客的标签
        blog.setTags(tagService.stringTagsToList(tagIds));
        // blog.setUserId(blog.getUser().getId());
        blog.setUserId(loginUser.getId());

        blogService.saveBlog(blog);
        return "redirect:/admin/blogs";
    }

    /**
     * 去修改博客页面
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/admin/blogs/{id}")
    public String toUpdatePage(@PathVariable("id") Long id, Model model) {
        saveTagAndType(model);
        UpdateBlog blog = blogService.getToUpdateBlogById(id);
        model.addAttribute("blog", blog);
        return "admin/blog-upd";
    }

    /**
     * 修改博客
     *
     * @param updateBlog
     * @param attributes
     * @return
     */
    @PutMapping("/admin/blogs/{id}")
    public String updateBlog(@PathVariable("id") Long id, UpdateBlog updateBlog, RedirectAttributes attributes) {
        int result = blogService.updateBlog(id, updateBlog);
        if (result >= 0) {
            attributes.addFlashAttribute("msg", "修改成功");
        } else {
            attributes.addFlashAttribute("msg", "修改失败");
        }

        return "redirect:/admin/blogs";
    }


}
